#!/sbin/openrc-run
# Copyright 2016-2018 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

description="Prometheus exporter for MySQL server metrics"

EXPORTER_FLAGS=${EXPORTER_FLAGS:-""}
EXPORTER_USER=${EXPORTER_USER:-"mysqld_exporter"}
EXPORTER_GROUP=${EXPORTER_GROUP:-"mysqld_exporter"}
EXPORTER_PIDFILE=${EXPORTER_PIDFILE:-"/run/${RC_SVCNAME}.pid"}
EXPORTER_SSDARGS=${EXPORTER_SSDARGS:-"--wait 1000"}
EXPORTER_TERMTIMEOUT=${EXPORTER_TERMTIMEOUT:-"TERM/60/KILL/5"}

command="/usr/bin/mysqld_exporter"
command_args="${EXPORTER_FLAGS}"
command_background="true"
start_stop_daemon_args="${EXPORTER_SSDARGS}"
start_stop_daemon_args="${start_stop_daemon_args} --user ${EXPORTER_USER}"
start_stop_daemon_args="${start_stop_daemon_args} --group ${EXPORTER_GROUP}"

# We are forcing log files because upstream is going to remove syslog support :/
start_stop_daemon_args="${start_stop_daemon_args} --stdout /var/log/mysqld_exporter/${RC_SVCNAME}.log"
start_stop_daemon_args="${start_stop_daemon_args} --stderr /var/log/mysqld_exporter/${RC_SVCNAME}.log"

getconfig() {
	local key="$1"
	local value_default="$2"
	local value=

	if service_started; then
		value="$(service_get_value "${key}")"
	fi

	if [ -z "${value}" ]; then
		# Value not explicitly set
		echo "${value_default}"
	else
		echo "${value}"
	fi

	return 0
}

pidfile="$(getconfig pidfile ${EXPORTER_PIDFILE})"
retry="$(getconfig retry ${EXPORTER_TERMTIMEOUT})"

configtest() {
	if test "${command_args#*config\.my-cnf}" = "${command_args}"; then
		local _default_config_file="/var/lib/mysqld_exporter/.my.cnf"
		if [ ! -s "${_default_config_file}" ]; then
			eerror "No MySQL credentials found in \"${_default_config_file}\"!"
			eerror "Either create that file and add credentials or specify another file via \"-config.my-cnf\" flag."
			return 1
		fi
	fi

	return 0
}

depend() {
	after net
	use mysql
}

start_pre() {
	if [ "${RC_CMD}" != "restart" ]; then
		configtest || return 1
	fi
}

start_post() {
	service_set_value retry "${EXPORTER_TERMTIMEOUT}"
}
